<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="收件人">
                <a-input
                  v-model="queryParam.receiver"
                  placeholder="请输入收件人姓名" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="发件人">
                <a-input
                  v-model="queryParam.sender"
                  placeholder="请输入发件人姓名" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="签收人">
                <a-input
                  v-model="queryParam.signer"
                  placeholder="请输入签收人姓名" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="快递内容">
                <a-input
                  v-model="queryParam.trackingContent"
                  placeholder="请输入快递内容姓名" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="发件日期">
                <a-range-picker
                  valueFormat="YYYY-MM-DD"
                  :placeholder="['开始日期','结束日期']"
                  v-model="queryParam.sendDate" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="签收日期">
                <a-range-picker
                  valueFormat="YYYY-MM-DD"
                  :placeholder="['开始日期','结束日期']"
                  v-model="queryParam.signDate" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button
                  type="primary"
                  v-if="list"
                  @click="searchExpress">查询</a-button>
                <a-button
                  style="margin-left: 8px"
                  v-if="list"
                  @click="() => {this.queryParam = {};this.$refs.table.refresh() }">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button
          type="primary"
          icon="plus"
          v-if="save"
          @click="handleAdd">新建</a-button>
      </div>
      <div>
        <s-table
          ref="table"
          size="default"
          rowKey="expressId"
          :columns="columns"
          :data="loadData"
          :customRow="tableCustomRow"
          showPagination="auto">
          <span
            slot="serial"
            slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span
            slot="sendDate"
            slot-scope="text, record">
            {{ record.sendDate? record.sendDate.split(' ')[0] : '' }}
          </span>
          <span
            slot="receiveDate"
            slot-scope="text, record">
            {{ record.receiveDate? record.receiveDate.split(' ')[0] : '' }}
          </span>
          <span
            slot="action"
            slot-scope="text, record">
            <template>
              <a v-if="update" @click="handleEdit(record)">配置</a>
              <a-divider type="vertical" />
              <a v-if="deleteBtn" @click="deleteExpressage(record.expressId)">删除</a>
            </template>
          </span>
        </s-table>
      </div>
      <create-form
        ref="createModal"
        :visible="visible"
        :fsave="fsave"
        :loading="confirmLoading"
        :isEdit="isEdit"
        @cancel="handleCancel"
        @ok="handleOk" />

      <div
        style="margin-top: 30px"
        v-show="express">
        <div class="table-operator">
          <span style="font-size: 20px;font-weight: bold;padding: 10px;padding-right: 30px">附件</span>
          <a-button
            type="primary"
            icon="plus"
            v-if="fupdate"
            @click="addFile">新建</a-button>
        </div>
        <a-spin :spinning="fileTabLoading">
          <a-table
            ref="fileTable"
            size="default"
            rowKey="fileId"
            :columns="fileColumns"
            :dataSource="files"
            :pagination="false">
            <span
              slot="serial"
              slot-scope="text, record, index">
              {{ index + 1 }}
            </span>
            <span
              slot="fileName"
              slot-scope="text, record">
              <a
                v-if="flist"
                target="blank"
                :href="record.fileUrl"
                :download="record.fileName">{{ record.fileName }}</a>
            </span>
            <span
              slot="action"
              slot-scope="text, record">
              <template>
                <a
                  @click="handleShowImg(record)">预览</a>
                <a-divider type="vertical" />
                <a v-if="fdeleteBtn" @click="handleDeleteFile(record)">删除</a>
              </template>
            </span>
          </a-table>
        </a-spin>
      </div>
      <file-create-form
        ref="fileCreateForm"
        :visible="fileCreateVisible"
        :loading="fileLoading"
        @cancel="handleFileCancel"
        @ok="handleFileOK" />
      <a-modal
        title="图片预览"
        width="800"
        :visible="showImg"
        :footer="null"
        @cancel="() => {this.showImg = false}">
        <div style="display: flex;justify-content: center">
          <img style="width: 700px" :src="imgUrl" />
        </div>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
// import moment from 'moment'
import { STable, Ellipsis } from '@/components'
// getExpressInfo, saveExpress, updateExpress, deleteExpress
import {
  getContact,
  getExpressList,
  saveContact,
  saveExpress,
  updateExpress,
  deleteExpress,
  getFileByIds,
  delFileById
} from '@/api/manage'
import CreateForm from './modules/CreateForm'
import FileCreateForm from './modules/FileCreateForm'
import { columns, fileColumns } from './config'
import { message, Modal } from 'ant-design-vue'
import { isInMenu } from '../config.js'
import { mapGetters } from 'vuex'

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    FileCreateForm
  },
  data () {
    this.columns = columns
    this.fileColumns = fileColumns
    return {
      // 预览
      showImg: false,
      imgUrl: '',
      // 权限参数
      list: false, // 列表
      save: false, // 加
      deleteBtn: false, // 删
      update: false, // 改
      // 文件权限
      // 权限参数
      flist: false, // 列表
      fsave: false, // 加
      fdeleteBtn: false, // 删
      fupdate: false, // 改

      // create model
      visible: false,
      fileCreateVisible: false,
      //
      confirmLoading: false,
      fileTabLoading: false,
      fileLoading: false,
      express: undefined,
      // 查询参数
      queryParam: {},
      // 附件
      files: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = { page: parameter.pageNo, limit: parameter.pageSize }
        const param = Object.assign({}, this.queryParam)
        if (this.queryParam.sendDate) {
          param.sendBeginDate = this.queryParam.sendDate[0]
          param.sendEndDate = this.queryParam.sendDate[1]
        }
        if (this.queryParam.signDate) {
          param.receiveBeginDate = this.queryParam.signDate[0]
          param.receiveEndDate = this.queryParam.signDate[1]
        }
        param.sendDate = undefined
        param.signDate = undefined
        return this.list && getExpressList(Object.assign({}, param, requestParameters, { entryDate: undefined })).then(res => {
          return Object.assign({}, res, {
            totalCount: res.total,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize
          })
        })
      },
      staffInfo: {},
      selectedRowKeys: [],
      selectedRows: [],
      physicalSurveyCurrRowId: null,
      isEdit: false
    }
  },
  created () {
    // 点击查看
    this.list = isInMenu(this.menu, 'ROLE_but:express:list') && isInMenu(this.menu, 'ROLE_but:express:info')
    // 增加
    this.save = isInMenu(this.menu, 'ROLE_but:express:save')
    // 改
    this.update = isInMenu(this.menu, 'ROLE_but:express:update')
    // 删除
    this.deleteBtn = isInMenu(this.menu, 'ROLE_but:express:delete')

    // 文件
    this.flist = isInMenu(this.menu, 'ROLE_but:expressFile:ids')
    // 增加
    this.fsave = isInMenu(this.menu, 'ROLE_but:expressFile:save')
    // 改
    this.fupdate = isInMenu(this.menu, 'ROLE_but:expressFile:update')
    // 删除
    this.fdeleteBtn = isInMenu(this.menu, 'ROLE_but:expressFile:delete')
  },
  computed: {
    ...mapGetters(['menu']),
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    deleteExpressage (expressId) {
      Modal.confirm({
        title: '删除快递信息',
        content: '删除后数据不再展示，需要查看请联系开发',
        onOk: () => {
          this.confirmLoading = true
          deleteExpress({ expressId })
            .then(() => {
              this.$refs.table.refresh()
              this.$message.success('删除成功')
              this.express = undefined
            })
            .finally(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    searchExpress () {
      this.$refs.table.refresh()
    },
    handleAdd () {
      this.isEdit = false
      this.visible = true
      this.$refs.createModal.form.resetFields()
    },
    handleEdit (record) {
      const form = this.$refs.createModal.form
      this.isEdit = true
      this.visible = true
      this.$nextTick(() => {
        form.setFieldsValue(record)
      })
    },
    handleOk () {
      const form = this.$refs.createModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
          if (!this.isEdit) {
            saveExpress(Object.assign({}, values)).then(res => {
              if (res.code === 0) {
                this.visible = false
                form.resetFields()
                this.$refs.createModal.resetFileList()
                this.$refs.table.refresh()
                this.$message.info('新增成功')
              }
            })
          } else {
            updateExpress(Object.assign({}, values)).then(res => {
              if (res.code === 0) {
                this.visible = false
                form.resetFields()
                this.$refs.createModal.resetFileList()
                this.$refs.table.refresh()
                this.$message.info('更新成功')
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        }
      })
    },
    handleCancel () {
      this.visible = false
      this.fileCreateVisible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
      this.$refs.fileCreateForm.form.resetFields()
    },
    tableCustomRow (record, index) {
      return {
                style: {
          'background-color': record.expressId === this.physicalSurveyCurrRowId ? '#dff3fe' : 'white'
        },
        on: {
          click: event => {
            this.physicalSurveyCurrRowId = record.expressId
            this.express = record
            this.flist && this.fileSearch(record)
          }
        }
      }
    },
    handleFileOK () {
      const form = this.$refs.fileCreateForm.form
      form.validateFields((errors, values) => {
        if (!errors) {
          const express = this.express
          if (express.fileIds) {
            express.fileIds = express.fileIds + ',' + values.fileIds
          } else {
            express.fileIds = values.fileIds
          }
          updateExpress(
            Object.assign(
              {},
              {
                expressId: express.expressId,
                fileIds: express.fileIds
              }
            )
          ).then(res => {
            if (res.code === 0) {
              this.fileCreateVisible = false
              form.resetFields()
              this.$refs.createModal.resetFileList()
              this.fileSearch(express)
              this.$message.info('新增成功')
            }
          })
        }
      })
    },
    handleFileCancel () {
      this.$refs.fileCreateForm.resetFileList()
      this.fileCreateVisible = false
    },
    addFile () {
      this.$refs.fileCreateForm.resetFileList()
      this.fileCreateVisible = true
    },
    handleDeleteFile (record) {
      const fileIds = this.express.fileIds.split(',')
      const newFileIds = []
      for (const id of fileIds) {
        if (id !== record.fileId.toString()) {
          newFileIds.push(id)
        }
      }
      this.express.fileIds = newFileIds.join(',')
      delFileById(
        Object.assign(
          {},
          {
            fileId: record.fileId
          }
        )
      ).then(res1 => {
        if (res1.code === 0) {
          updateExpress(
            Object.assign(
              {},
              {
                expressId: this.express.expressId,
                fileIds: this.express.fileIds
              }
            )
          ).then(res => {
            if (res.code === 0) {
              this.fileSearch(this.express)
              this.$message.info('删除成功')
            }
          })
        }
      })
    },
    fileCreateOK () {
      // relationId type S
      const form = this.$refs.fileCreateForm.form
      form.validateFields((errors, values) => {
        if (!errors) {
          saveContact(Object.assign({}, values, { type: 2, relationId: this.supplier.supplierId })).then(() => {
            this.customLoading = false
            this.contactCreateVisible = false
            message.success('新增成功')
            this.contactTabLoading = true
            getContact({ relationId: this.supplier.supplierId, type: 2, page: 1, limit: 100 }).then(res => {
              this.contacts = res.data
              this.contactTabLoading = false
            })
          })
        }
      })
    },
    fileSearch (record) {
      if (record.fileIds) {
        getFileByIds({ fileIds: record.fileIds }).then(res => {
          this.files = res.data
        })
      } else {
        this.files = []
      }
    },
    handleShowImg (record) {
      this.showImg = true
      this.imgUrl = record?.fileUrl
    }
  }
}
</script>
